import { app, shell, BrowserWindow, ipcMain } from 'electron'
import path, { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import icon from '../../resources/icon.png?asset'
import child_process from "child_process";
const process = require('process')
import log from "electron-log"
const redirectLog = () => {
  console.log = log.log;
  console.error = log.error;
  console.warn = log.warn;
  console.info = log.info;
  console.debug = log.debug;
};
const appRootPath = app.getAppPath();
const devRootPath = appRootPath;
const prodRootPath = getParentOfFolder("resources", appRootPath);
redirectLog();
if (is.dev) {
  log.transports.file.resolvePathFn = () => path.join(devRootPath, "logs/main.log");
  log.info("devRootPath: " + devRootPath);
} else {
  log.transports.file.resolvePathFn = () => path.join(prodRootPath, "logs/python.log");
  log.info("prodRootPath: " + prodRootPath);
}
function createWindow() {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 1080,
    frame:false,
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      // sandbox: false,
      nodeIntegration: true, //是否集成node
      // devTools:false,//是否开启 DevTools
      webSecurity: false //是否禁用同源策略(上线时删除此配置)
    }
  })
  if (!is.dev){
    // mainWindow.setFullScreen(true)
  }
  // mainWindow.setFullScreen(true)


  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })
  ipcMain.on('close', () => {
    mainWindow.close()
  })
  ipcMain.on('test', () => {
    console.log('test')
  })

  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  // Set app user model id for windows
  electronApp.setAppUserModelId('com.electron')
  if (!is.dev) {
    // startPythonService();
  }
  // Default open or close DevTools by F12 in development
  // and ignore CommandOrControl + R in production.
  // see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  createWindow()

  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})
app.on("before-quit", () => {
  if (!is.dev){
    // stopPythonService();
  }
});

// In this file you can include the rest of your apps specific main process
// code. You can also put them in separate files and require them here.
// let pythonProcess = child_process.spawn("python", [path.join(prodRootPath, "main.py")]);
function startPythonService() {
  pythonProcess.stdout.on("data", (data) => {
    console.log(`stdout: ${data}`);
  });
  pythonProcess.stderr.on("data", (data) => {
    console.error(`stderr: ${data}`);
  });
  pythonProcess.on("close", (code) => {
    console.log(`Python service exited with code ${code}`);
  });
}
function stopPythonService() {
  if (pythonProcess) {
    pythonProcess.kill();
    log.info("Python服务已停止");
    pythonProcess = null;
  }
}
function getParentOfFolder(targetFolder, filePath) {
  const parts = filePath.split(path.sep);
  const targetIndex = parts.indexOf(targetFolder);
  if (targetIndex > 0) {
    return parts.slice(0, targetIndex).join(path.sep);
  } else {
    return filePath;
  }
}
